package com.example.vueblog.filter;

import com.example.vueblog.common.utils.JwtTokenUtil;
import com.example.vueblog.security.MyUserDetailsService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 确保在一次请求只通过一次filter，而不需要重复执行
 *
 * @author yushunshun
 * @date 2022/5/28 22:12
 */
@Component
@Slf4j
@Order(2)
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    MyUserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //校验jwt
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String authToken = authHeader.substring("Bearer ".length());

            //根据jwtToken解析获取主体对象并校验该token是否过期
            Claims claim = JwtTokenUtil.getClaimByToken(authToken);
            if (claim != null && !JwtTokenUtil.isTokenExpired(claim.getExpiration())) {
                //如果上下文中没有改用户则设置
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    //查询用户信息
                    UserDetails userDetails = null;
                    try {
                        userDetails = userDetailsService.loadUserByUsername(claim.getSubject());
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } catch (Exception e) {
                        filterChain.doFilter(request, response);
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
